package com.example.controller;

import com.example.pojo.User;
import com.example.service.UserService;
import com.example.util.PageUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;
import java.util.Map;

@Controller
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("page")
    public String page(@RequestParam Map<String,String> map, Model model){
        List<User> users=userService.findAll(null);
        log.info("执行查询");
        if (map.size()==0 || map.get("currentPage").isEmpty()){
            map.put("currentPage","1");
        }
        PageUtil currentPage=new PageUtil(Integer.valueOf(map.get("currentPage")),2,users);
        model.addAttribute("users",currentPage.getList());
        model.addAttribute("currentPage",currentPage);
        return "users";
    }

    @RequestMapping("toAdd")
    public String toAdd(Model model){
        User users = new User();
        model.addAttribute("users",users);
        System.out.println("执行到添加页面");
        return "add";
    }

    @RequestMapping("/add")
    public String add(Model model,User user){
        System.out.println("跳转添加方法");
        userService.add(user);
        System.out.println("执行重新查询");
        return "redirect:/page";
    }

    @RequestMapping("findById")
    public String findById(Model model,String id){
        User user= userService.findById(id);
        System.out.println("执行查询id");
        model.addAttribute("users",user);
        System.out.println("跳转到修改页面");
        return "update";
    }

    @RequestMapping("update")
    public String update(Model model,User user){
        System.out.println("执行修改方法");
        userService.update(user);
        System.out.println("执行重新查询");
        return "redirect:/page";
    }

    @RequestMapping("del")
    public String del(String id){
        System.out.println("执行删除方法");
        userService.del(id);
        System.out.println("跳转到重新查询");
        return "redirect:/page";
    }
}
